import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login/Login.vue'
import AdReportForms from "../views/reportData/adReportForms/adReportForms.vue"
import { getToken } from '../utils/auth'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: "/",
    name: "Home",
    redirect: "/adReportForms"
  },
  {
    path: '/adReportForms',
    name: 'adReportForms',
    meta: {
      title: "测试"
    },
    component: AdReportForms
  },
  {
    path: '/404',
    name: '404',
    url: '/404',
    component: () => import('../views/error/404.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

const whiteList = ['/login']; //不重定向白名单
router.beforeEach((to, from, next) => {
  document.title = to?.meta?.title || '海外投放-h5'
  let token = getToken();
  
  if (token) { //登录token存在
    if (to.path == '/login') {
      next({ path: "/" })
    } else {
      if (to.matched.length === 0) {
        // 没有找到页面跳转到404
        from.name ? next({ name: from.name }) : next('404');
      } else {
        next()
      }
    }
  }else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
